
% expected commandline arguments:
%filename = 'vars_label_assetclass1_....csv';
%multi= 0 or multi = 1;
% example: filename='vars_dhw_US_FXdev_Onew90.csv'; multi=0;


opts = detectImportOptions(strcat('../OutputInterim/MatlabInput/',filename));
data_full = readmatrix(strcat('../OutputInterim/MatlabInput/',filename),opts,'OutputType','double');

classnames = split(extractBefore(filename,'.'),'_');
nclasses = length(classnames)-2;
nassets = sum(startsWith(opts.VariableNames,"eret"));
nvars = length(opts.VariableNames)-nassets;

assetclasses = zeros(1,nvars+nassets);
for i = 1:nclasses
    assetclasses = assetclasses + i * contains(string(opts.VariableNames),classnames{2+i});
end

assetclasses(1,1:nvars) = zeros(1,nvars);

factors = data_full(:,1:nvars);

if multi == 0
    wvals = zeros(nclasses,1);
    pvals = zeros(nclasses,1);

    for i=1:nclasses

        rets = data_full(:,assetclasses==i);

        cmnsample = all(~isnan(horzcat(factors,rets)),2);
    
        factorsi = factors(cmnsample,:);
        rets = rets(cmnsample,:);
    
        [~, pval_Wald, pval_F] = rank_eig(rets',factorsi');
        wvals(i)=pval_Wald;
        pvals(i)=pval_F;
   
    end
    
    names = string(classnames);
    names = names(3:end);
else
    wvals = zeros(1,1);
    pvals = zeros(1,1);
    
    rets = data_full(:,assetclasses>0);
    cmnsample = all(~isnan(horzcat(factors,rets)),2);
    
    T = sum(cmnsample)
    N = sum(assetclasses>0)
    
    factorsi = factors(cmnsample,:);
    rets = rets(cmnsample,:);
    
    acs = assetclasses(assetclasses>0);
    
    [~, pval_Wald, pval_F] = rank_eig_multiasset(rets',factorsi',acs');
    wvals(1)=pval_Wald;
    pvals(1)=pval_F;
    
    names = string({'all'});
end

outfile = strcat('../OutputInterim/MatlabInput/output_',filename);

tbl = table(names,wvals,pvals);

writetable(tbl,outfile);

wvals
pvals

